package org.dxy.domain.handler.workstation;

import com.google.common.eventbus.EventBus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.port.CommandHandler;
import org.dxy.domain.port.repository.IWorkstationRepository;
import org.dxy.domain.command.workstation.ReportWorkstationErrorCommand;
import org.dxy.domain.model.aggregate.Workstation;
import org.dxy.types.common.CommandResult;
import org.springframework.stereotype.Component;

/**
 * @description: 工位错误报告命令处理器
 * @author: dxy
 * @createTime: 2025/6/18 22:07
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ReportWorkstationErrorCommandHandler implements CommandHandler<ReportWorkstationErrorCommand, Void> {

    private final IWorkstationRepository workstationRepository;
    private final EventBus eventBus;

    @Override
    public CommandResult<Void> handle(ReportWorkstationErrorCommand command) {
        Workstation workstation = workstationRepository.findById(command.getWorkstationId());
        if (workstation == null) {
            log.error("未找到工位，command={}", command);
            return CommandResult.fail("工位不存在");
        }

        try {
            workstation.reportError(command);
            workstationRepository.save(workstation);
            workstation.getDomainEvents().forEach(eventBus::post);
            workstation.clearDomainEvents();
            
            log.info("工位错误报告成功, command={}", command);
            return CommandResult.success("工位错误报告成功");
        } catch (IllegalStateException e) {
            log.warn("工位错误报告失败，原因：{}", e.getMessage());
            return CommandResult.fail(e.getMessage());
        }
    }
}

